﻿using AutoMapper;
using B.S.BaseData.Api.Read.Command.GoodsCommand;
using B.S.BaseData.ErrorCode;
using B.S.BaseData.Infrastructure.Interface;
using B.S.BataBase.Domain.DTO.GoodsDTO;
using B.S.BataBase.Domain.Entitys;
using MediatR;

namespace B.S.BaseData.Api.Read.CommandHandler.GoodsCommandHandler
{
    public class GoodsInfoShowCommandHandler : IRequestHandler<GoodsInfoShowCommand, APIResult<ApiPaging<GoodInfoDTO>>>
    {
        private readonly IBaseRepository<GoodsInfo> _goodsbaseRepository;
        private readonly IMapper _mapper;
        private readonly IBaseRepository<GoodsType> _goodssTypeRepository;
        public GoodsInfoShowCommandHandler(IBaseRepository<GoodsInfo> goodsbaseRepository, IMapper mapper, IBaseRepository<GoodsType> goodssTypeRepository)
        {
            _goodsbaseRepository = goodsbaseRepository;
            _mapper = mapper;
            _goodssTypeRepository = goodssTypeRepository;
        }
        public async Task<APIResult<ApiPaging<GoodInfoDTO>>> Handle(GoodsInfoShowCommand request, CancellationToken cancellationToken)
        {
            APIResult<ApiPaging<GoodInfoDTO>> result=new APIResult<ApiPaging<GoodInfoDTO>>();
            var list= _goodsbaseRepository.GetAll().Where(x=>x.IsDeleted==false);
            if (request.goodsName != null)
            {
                list = list.Where(x => x.GoodsName == request.goodsName);
            }
            var res= _mapper.Map<List<GoodInfoDTO>>(list);
            foreach (var item in res)
            {
                item.GoodsTypeName=(await _goodssTypeRepository.GetValues(x=>x.Id==item.GoodsName)).GoodTypeName;
            }
            var totaCount= res.Count();
            var pageCount = (int)Math.Ceiling(totaCount*1.0/request.pageSize);
            ApiPaging<GoodInfoDTO> paging=new ApiPaging<GoodInfoDTO>();
            paging.TotalPage = pageCount;
            paging.Total = totaCount;
            paging.PageData = res.Skip((request.pageIndex-1)*request.pageSize).Take(request.pageSize).ToList();
            result.Data = paging;
            result.Code = ApiEnum.Success;
            result.Msg = "商品列表显示成功";
            return await Task.FromResult(result);
        } 
    }
}
